<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 300px;" class="filter-item" placeholder="名称" v-model="whereQuery.name"></el-input>
      <el-select class="filter-item" v-model="whereQuery.did" clearable filterable remote placeholder="请输入设备编号" :remote-method="remoteMethod" @change="handleFilter" :loading="deviceLoading">
        <el-option v-for="item in deviceOptions" :key="item.id" :label="item.number" :value="item.id">
        </el-option>
      </el-select>
      <el-select clearable style="width: 120px" class="filter-item" v-model="whereQuery.status" placeholder="状态" @change="handleFilter">
        <el-option v-for="item in statusOptions" :key="item" :label="item | statusFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200" header-align="center" label='名称' show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="140px" header-align="center" label="设备" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.did" @click="showJsonObject(scope.row.did)">{{scope.row.did.number}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="80px" header-align="center" align="center" label='状态'>
        <template slot-scope="scope">
          <span>{{scope.row.status | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200px" header-align="center" label='说明' show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.info}}</span>
        </template>
      </el-table-column>
      <el-table-column width="155" align="center" label="发出时间">
        <template slot-scope="scope">
          <span>{{scope.row.sendTime | momentFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column width="155" align="center" label="激活时间">
        <template slot-scope="scope">
          <span>{{scope.row.activeTime | momentFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column width="155" align="center" label="收回时间">
        <template slot-scope="scope">
          <span>{{scope.row.backTime | momentFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button v-bind:disabled="scope.row.status === 4" size="mini" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status === 1"  size="mini" type="success" @click="changeStatus(scope.row, 2)">发送</el-button>
          <el-button v-else v-bind:disabled="scope.row.status === 4" size="mini" type="success" @click="changeStatus(scope.row, 4)">收回</el-button>
          <el-button v-bind:disabled="scope.row.status > 1" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" v-bind:disabled="temp.status !== undefined && temp.status > 1"></el-input>
        </el-form-item>
        <el-form-item label="设备编号" prop="did">
          <el-select style="width: 100%;" v-model="temp.did" clearable filterable remote placeholder="请输入设备编号" :remote-method="remoteMethod" :loading="deviceLoading" v-bind:disabled="temp.status !== undefined && temp.status > 1">
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.number" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入内容" v-model="temp.info"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { saveDistribution, listDistribution, deleteDistribution, listDevice, updateDistributionStatus } from '@/api/monitor'
  import waves from '@/directive/waves'
  import { MessageBox, Message } from 'element-ui'

  export default {
    name: 'distribution',
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        devices: undefined,
        total: null,
        listLoading: true,
        listQuery: {
          page: 0,
          size: 10,
          did: undefined,
          status: undefined,
          name: undefined
        },
        whereQuery: {
          did: undefined,
          status: undefined,
          name: undefined
        },
        temp: {
          id: undefined,
          name: undefined,
          did: undefined,
          status: undefined,
          sendTime: undefined,
          activeTime: undefined,
          backTime: undefined,
          info: undefined
        },
        listDeviceQuery: {
          page: 0,
          size: 10,
          number: undefined
        },
        deviceOptions: [],
        statusOptions: [1, 2, 3, 4],
        dialogFormVisible: false,
        jsonVisible: false,
        deviceLoading: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
          did: [{ required: true, message: '设备不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      json: (value) => { return JSON.stringify(value, null, 2) },
      statusFilter(stauts) {
        const statusList = ['待发出', '已发出', '已激活', '已收回']
        return stauts > 0 ? statusList[stauts - 1] : ''
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        this.listQuery.name = this.whereQuery.name
        this.listQuery.did = this.whereQuery.did
        if (this.whereQuery.status !== undefined) {
          this.listQuery.status = this.whereQuery.status
        }
        listDistribution(this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.devices = response.data.data.devices
          this.list.forEach(value => {
            const did = value.did
            if (did !== undefined) {
              value.did = this.devices[did]
            }
          })
          this.listLoading = false
        })
      },
      remoteMethod(keyword) {
        if (this.deviceLoading) {
          return
        }
        if (keyword !== '') {
          this.deviceLoading = true
          setTimeout(() => {
            this.deviceLoading = false
            this.listDeviceQuery.number = keyword
            listDevice(this.listDeviceQuery).then(response => {
              this.deviceOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.deviceOptions = []
        }
      },
      handleFilter() {
        this.listQuery.page = 0
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val - 1
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: undefined,
          did: undefined,
          status: undefined,
          sendTime: undefined,
          activeTime: undefined,
          backTime: undefined,
          info: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.deviceOptions = []
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            saveDistribution(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (this.temp.did) {
          this.deviceOptions.push(this.temp.did)
          this.temp.did = this.temp.did.id
        } else {
          this.temp.did = undefined
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            saveDistribution(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteDistribution(row.id).then(response => {
            if (response.status === 200) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        }, () => {})
      },
      changeStatus(row, status) {
        if (!row.did) {
          Message({
            message: '设备信息缺失，请检查',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        var op = ''
        var info = ''
        if (status === 2) {
          op = '发送'
          info = '是否执行发送操作？'
        } else if (status === 4) {
          op = '收回'
          if (row.status === 2) {
            info = '该设备本次尚未激活，请确认物理设备已经收回，否则执行收回后，设备相关操作记录可能出现错误！！！'
          } else {
            info = '是否执行收回操作？该操作将成功后将无法撤回！'
          }
        }
        MessageBox.confirm(info, row.name, {
          confirmButtonText: op,
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateDistributionStatus(row.id, status).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: op + '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        }, () => {})
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      }
    }
  }
</script>

